#!/usr/bin/perl

# Usage:  manisort [-q] [-o outfile] [filename]
#
# Without 'filename', looks for MANIFEST in the current dir.
# With '-o outfile', writes the sorted MANIFEST to the specified file.
# Prints the result of the sort to stderr.  '-q' silences this.
# The exit code for the script is the sort result status
# (i.e., 0 means already sorted properly, 1 means not properly sorted)

use strict;
use warnings;
$| = 1;

# Get command line options
use Getopt::Long;
require "./Porting/manifest_lib.pl";
my $outfile;
my $check_only = 0;
my $quiet = 0;
GetOptions ('output=s' => \$outfile,
            'check'    => \$check_only,
            'quiet'    => \$quiet);

my $file = (@ARGV) ? shift : 'MANIFEST';

# Read in the MANIFEST file
open(my $IN, '<', $file)
    or die("Can't read '$file': $!");
my @manifest = <$IN>;
close($IN) or die($!);
chomp(@manifest);

my %seen= ( '' => 1 ); # filter out blank lines
my @sorted = grep { !$seen{$_}++ }
             sort_manifest(@manifest)
;

# Check if the file is sorted or not
my $exit_code = 0;
for (my $ii = 0; $ii < $#manifest; $ii++) {
    next if ($manifest[$ii] eq $sorted[$ii]);
    $exit_code = 1;   # Not sorted
    last;
}

# Output sorted file
if (defined($outfile)) {
    open(my $OUT, '>', $outfile)
        or die("Can't open output file '$outfile': $!");
    binmode($OUT);
    print($OUT join("\n", @sorted), "\n");
    close($OUT) or die($!);
}

# Report on sort results
printf(STDERR "'$file' is%s sorted properly\n",
            (($exit_code) ? ' NOT' : '')) if (! $quiet);

# Exit with the sort results status
exit($exit_code);

# EOF
